import datetime,cgi
import sys
import os
from google.appengine.ext.webapp import template
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.dist import use_library
from os import environ
from models import *

class MeetMe(webapp.RequestHandler):
	def post(self):
		userdetails=db.GqlQuery("SELECT * FROM userDetails")
	        details=[]
	        for i in userdetails:
                        temp=[]
                        temp.append(i.admissionnumber)
                        temp.append(i.username)
                        details.append(temp)
		date=self.request.get("date")
		note="Administrator says: come and meet me on '%s'" %date
		for i in details :
			if self.request.get(i[0])=="yes":
				newnote=notificationDetails(admissionnumber=i[0],notification=note)
				key=newnote.put()
				idnum=key.id()
				newnote.notificationid=str(idnum)
				newnote.put()
		self.redirect("/meetme")
	def verifyLogin(self):
		user = users.get_current_user()
		if user:
			usercheck=userDetails.all()
			usercheck.filter("email =",user.email())
			try:
				currentuser=usercheck.fetch(1)[0]
				userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'")
				for i in userdet:
					if i.privilege=='admin':
						return
					elif i.approved==False:
						self.redirect("/usererror")
						return
				self.redirect("/user")
			except:
				path = os.path.join(os.pathi.admissionnumber.dirname(__file__),'form.html')#use template
				self.response.out.write(template.render(path,{"email":user.email()}))#using template
		else:
			self.redirect(users.create_login_url(self.request.uri))

	def get(self):
		self.verifyLogin()
	        userdetails=db.GqlQuery("SELECT * FROM userDetails")
	        details=[]
	        for i in userdetails:
                        temp=[]
                        temp.append(i.admissionnumber)
                        temp.append(i.username)
                        details.append(temp)

		path = os.path.join(os.path.dirname(__file__),'meetme.html')#use template
		self.response.out.write(template.render(path,{"details":details}))#using template

application = webapp.WSGIApplication([('/meetme', MeetMe)], debug=True)

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()
